//
//  SSQRCodeViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/2/20.
//

import UIKit
import AVFoundation
import Photos
import Alamofire
import SwiftyJSON


class SSQRCodeViewController: SSBaseViewController,UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate {
    
    let accessBlock = {(response:Bool) in
        
    }
    @IBOutlet weak var closeBtn: UIButton!
    @IBOutlet weak var QRCodeImgV: UIImageView!
    
    @IBOutlet weak var textLab: UILabel!
    
    @IBOutlet weak var whiteView: UIView!
    @IBOutlet weak var textLab1: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.1)
        whiteView.cornerRadius( radius: 20,corners: [UIRectCorner.topLeft, UIRectCorner.topRight])
        closeBtn.ssc_expandSize(size: 50)
//        whiteView.cornerRadius(radius: 8, corners: .topLeft|.topRight)
        getQRCodeNetwork()
    }
    
    //qrcode
    func getQRCodeNetwork() {
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.getVxImg_URL, parameters: nil) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["retMsg"].stringValue
                if(retCode == "0000"){
                    let url = json["data"]["vxImgUrl"].string
                    self.QRCodeImgV.setImage(with: url, placeholderImage: UIImage(named: "")) { image, error in
                    }
                }else{
                    dissmissToTast(msg: "\(retMsg)")
                }
            }
        }
    }

    @IBAction func QRCodeAction(_ sender: Any) {
        accessCameraAuthority { b in
            
        }
    }
    
    @IBAction func closeAction(_ sender: Any) {
        dismiss(animated: true)
    }
    /// 获取权限
    ///
    /// - Parameter accessBlock:  闭包回调
    func accessCameraAuthority(accessBlock: ((Bool) -> Void)? = nil)
    {
        
        let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
        if(library == PHAuthorizationStatus.authorized){
//            self.view.makeToast("authorized")
            let image = UIImage()
            UIImageWriteToSavedPhotosAlbum(QRCodeImgV.image ?? image, self, #selector(save(image:didFinishSavingWithError:contextInfo:)), nil)
        } else if(library == PHAuthorizationStatus.notDetermined){
//            self.view.makeToast("notDetermined")
            let image = UIImage()
            UIImageWriteToSavedPhotosAlbum(QRCodeImgV.image ?? image, nil, nil, nil)
        }else{
            let alertView = EtcAlertView(title: "照片访问受限", message: "点击“设置”，允许访问您的照片", cancleTitle:"取消", confirmTitle: "设置")
            alertView.showAlert(confirm:  {
                let url = URL(string: UIApplication.openSettingsURLString)
                if let url = url, UIApplication.shared.canOpenURL(url) {
                    if #available(iOS 10, *) {
                        UIApplication.shared.open(url, options: [:],
                                                  completionHandler: {
                                                    (success) in
                        })
                    } else {
                       UIApplication.shared.openURL(url)
                    }
                }
            }) {
                
            }
        }

    }
    
   @objc func save(image:UIImage, didFinishSavingWithError:NSError?,contextInfo:AnyObject) {
         
         if didFinishSavingWithError != nil {
             self.view.makeToast("保存失败")
         } else {
             self.view.makeToast("保存成功")
         }
     }
    
}


extension UIView {
    
    /// 圆角优化 离屏渲染优化方案
    func cornerRadius(radius: CGFloat, corners: UIRectCorner) {
        let bezierPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let radiusLayer = CAShapeLayer()
        radiusLayer.frame = self.bounds
        radiusLayer.path = bezierPath.cgPath
        self.layer.mask = radiusLayer
    }
    
    func cornerRadius(radius: CGFloat, corners: UIRectCorner, color: UIColor, lineWidth: CGFloat) {
        let bezierPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let radiusLayer = CAShapeLayer()
        radiusLayer.frame = self.bounds
        radiusLayer.path = bezierPath.cgPath
        self.layer.mask = radiusLayer
        // 添加border
        let borderLayer = CAShapeLayer()
        borderLayer.frame = self.bounds
        borderLayer.path = bezierPath.cgPath
        borderLayer.lineWidth = lineWidth
        borderLayer.strokeColor = color.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor
        if let layers: NSArray = self.layer.sublayers as? NSArray {
            if let last = layers.lastObject as? AnyObject {
                if last.isKind(of: CAShapeLayer.self) {
                    last.removeFromSuperlayer()
                }
            }
        }
        self.layer.addSublayer(borderLayer)
    }
    
    func cornerRadius(radius: CGFloat, corners: UIRectCorner, bounds: CGRect) {
        let bezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let radiusLayer = CAShapeLayer()
        radiusLayer.frame = bounds
        radiusLayer.path = bezierPath.cgPath
        self.layer.mask = radiusLayer
    }
  
}
